from django.http import JsonResponse
from django.views.generic import View
from common.utils.ip import get_ip
from common.models import Commits
from user.utils.options import get_options


class Commit(View):
    def post(self, request):
        name = request.POST.get('name')
        student_id = request.POST.get('studentID')
        phone = request.POST.get('phone')
        email = request.POST.get('email')

        dic = {
            'name': name,
            'studentID': student_id,
            'phone': phone,
            'email': email
        }

        lis = get_options()
        # print("#######")
        # print(lis[1]['key'])

        content = {
            "code": 0,
            "message": "OK"
        }

        flag = True

        for element in lis:
            if dic[element['key']] == '' or dic[element['key']] is None:
                if element['must'] is True:
                    content = {
                        "code": 1,
                        "message": element['name'] + "is null"
                    }
                    flag = False
                    break
                else:
                    dic[element['key']] = 'Null'

        if flag:
            Commits.objects.create(
                ip=get_ip(request.META),
                options=dic
            )

        return JsonResponse(content)
